<script setup>
import { ref, reactive, computed, onMounted, watch, onBeforeUnmount, nextTick } from 'vue'
import { useItemsStore } from '../../stores/items'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import {
  Plus, Grid, Menu, Edit, Delete, HomeFilled,
  Setting, Star, Location, ArrowDown, More,
  OfficeBuilding, ShoppingBag, Food, Cpu,
  ArrowRight // 导入右箭头图标
} from '@element-plus/icons-vue'
import IconSvg from '../../components/icons/IconSvg.vue'
import ItemDetailModal from '../../components/items/ItemDetailModal.vue' // 导入新组件

const itemsStore = useItemsStore()

const viewMode = ref('grid') // 'grid' 或 'list'
const searchQuery = ref('')
const showLocationSelector = ref(false)
const selectedLocationId = ref(null)

// 新增：控制详情编辑模态框的状态
const detailModalVisible = ref(false)
const itemToEdit = ref(null)

// 控制添加物品对话框的状态
const addDialogVisible = ref(false)

// 当前选中的位置名称
const currentLocation = computed(() => {
  if (!selectedLocationId.value) return null
  const location = itemsStore.locations.find(l => l.id === selectedLocationId.value)
  return location ? location.name : null
})

// 切换位置选择器显示状态
const toggleLocationSelector = () => {
  showLocationSelector.value = !showLocationSelector.value
}

// 选择位置
const selectLocation = (locationId) => {
  selectedLocationId.value = locationId
  filters.locationId = locationId
  showLocationSelector.value = false
  
  // 保存当前选择的位置ID到localStorage，确保是字符串格式
  if (locationId) {
    localStorage.setItem('currentLocationId', locationId.toString())
    console.log('位置ID已保存到localStorage:', locationId.toString());
  } else {
    localStorage.removeItem('currentLocationId')
    console.log('已从localStorage移除位置ID');
  }
  
  // 构建URL确保位置ID被正确添加
  const baseUrl = '/dashboard/home';
  const url = locationId ? `${baseUrl}?locationId=${encodeURIComponent(locationId.toString())}` : baseUrl;
  console.log('准备跳转到URL:', url);
  
  // 使用window.location.href强制刷新页面
  window.location.href = url;
}

// 点击外部关闭下拉菜单
const closeLocationSelector = (event) => {
  const selector = document.querySelector('.location-selector')
  if (selector && !selector.contains(event.target)) {
    showLocationSelector.value = false
  }
}

// 添加和移除全局点击事件监听
onMounted(() => {
  document.addEventListener('click', closeLocationSelector)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeLocationSelector)
  window.removeEventListener('scroll', handleScroll)
  // 清除观察器
  if (loadingObserver.value) {
    loadingObserver.value.disconnect()
    console.log('已清除IntersectionObserver')
  }
})

// 过滤条件
const filters = reactive({
  categoryId: null,
  locationId: null,
  status: null,
  sortBy: 'name', // 默认按名称排序
  sortOrder: 'asc'
})

// 新增：加载更多物品的状态控制
const loadingMore = ref(false)
const allItemsLoaded = ref(false)

// 修改监听搜索和过滤变化，更新store中的过滤条件
watch(searchQuery, (val) => {
  // 当搜索条件变化时，重置所有相关状态
  allItemsLoaded.value = false;
  // 确保页面大小保持为12
  itemsStore.setFilters({ search: val, pageSize: 12 });
});

watch(filters, (val) => {
  // 当过滤条件变化时，重置所有相关状态
  allItemsLoaded.value = false;
  // 确保页面大小保持为12
  itemsStore.setFilters({ ...val, pageSize: 12 });
}, { deep: true });

// 获取物品列表和过滤后的物品
const items = computed(() => {
  // 确保从store获取的数据是有效的数组
  const storeItems = itemsStore.getFilteredItems;
  console.log('Store items type:', typeof storeItems, 'isArray:', Array.isArray(storeItems));
  console.log('Store items:', JSON.stringify(storeItems));
  
  // 检查是否是后端返回的响应格式 ({code, message, data: {records: [...]}})
  if (storeItems && storeItems.data && storeItems.data.records && Array.isArray(storeItems.data.records)) {
    console.log('检测到后端原始响应格式，返回 records 数组');
    return storeItems.data.records;
  }
  
  // 检查是否是已处理的 rawResponse
  if (storeItems && storeItems.items && Array.isArray(storeItems.items)) {
    console.log('检测到 rawResponse 格式，返回 items 数组，长度:', storeItems.items.length);
    return storeItems.items;
  }
  
  // 检查是否是数组类型，如果是直接返回
  if (Array.isArray(storeItems)) {
    console.log('检测到数组格式，直接返回，长度:', storeItems.length);
    return storeItems;
  }

  // 如果是对象且有records属性（后端返回的格式），直接返回records数组
  if (storeItems && storeItems.records && Array.isArray(storeItems.records)) {
    console.log('检测到对象包含 records 数组，返回 records，长度:', storeItems.records.length);
    return storeItems.records;
  }

  // 如果是对象且有items属性，返回items属性
  if (storeItems && typeof storeItems === 'object' && Array.isArray(storeItems.items)) {
    console.log('检测到对象包含 items 数组，返回 items，长度:', storeItems.items.length);
    return storeItems.items;
  }

  // 如果store中没有有效数据，尝试从store的items字段获取
  if (Array.isArray(itemsStore.items)) {
    console.log('从 itemsStore.items 获取数组数据，长度:', itemsStore.items.length);
    return itemsStore.items;
  }
  
  // 如果itemsStore.items是对象且包含records属性
  if (itemsStore.items && typeof itemsStore.items === 'object' && Array.isArray(itemsStore.items.records)) {
    console.log('从 itemsStore.items.records 获取数组数据');
    return itemsStore.items.records;
  }

  // 如果上述都失败，返回空数组避免页面错误
  console.log('未找到有效数据，返回空数组');
  return [];
})
const categories = computed(() => itemsStore.categories)
const locations = computed(() => itemsStore.locations)
const statuses = computed(() => itemsStore.statuses)
const loading = computed(() => itemsStore.loading)
const pagination = computed(() => itemsStore.pagination)

// 计算总资产价值
const totalAssetValue = computed(() => {
  return items.value.reduce((sum, item) => sum + Number(item.price || 0), 0).toFixed(2)
})

// 计算平均每日成本
const averageDailyCost = computed(() => {
  const total = items.value.reduce((sum, item) => {
    return sum + getDailyCost(item) * item.quantity
  }, 0)
  return (total / Math.max(1, items.value.length)).toFixed(2)
})

// 在役物品数量
const activeItemsCount = computed(() => {
  return items.value.filter(item => item.status === 'active').length
})

// 退役物品数量
const inactiveItemsCount = computed(() => {
  return items.value.filter(item => item.status !== 'active').length
})

// 计算物品拥有天数
const getOwnedDays = (item) => {
  if (!item.purchaseDate) return 0
  const purchaseDate = new Date(item.purchaseDate)
  const today = new Date()
  const diffTime = Math.abs(today - purchaseDate)
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

// 计算物品每日成本
const getDailyCost = (item) => {
  const days = getOwnedDays(item)
  if (days === 0) return 0
  return (item.price / days).toFixed(1)
}

// 获取分类图标
const getCategoryIcon = (categoryId) => {
  // 根据分类返回不同的图标
  const category = categories.value.find(c => c.id === categoryId)
  if (!category) return '/icons/default.png'

  switch (category.name) {
    case '电子设备': return '/icons/electronics.png'
    case '家具': return '/icons/furniture.png'
    case '厨房用品': return '/icons/kitchen.png'
    case '卫浴用品': return '/icons/bathroom.png'
    default: return '/icons/default.png'
  }
}

// 获取物品卡片的类名
const getItemCardClass = (item) => {
  let classes = [];
  
  // 添加分类相关类名
  if (!item.categoryId) {
    classes.push('card-default');
  } else {
    const category = categories.value.find(c => c.id === item.categoryId);
    if (!category) {
      classes.push('card-default');
    } else {
  switch (category.name) {
        case '电子设备': classes.push('card-electronics'); break;
        case '家具': classes.push('card-furniture'); break;
        case '厨房用品': classes.push('card-kitchen'); break;
        case '卫浴用品': classes.push('card-bathroom'); break;
        case '电器': classes.push('card-appliance'); break;
        case '相机': classes.push('card-camera'); break;
        default: classes.push('card-default'); break;
  }
    }
  }
  
  // 如果是消耗品，添加consumable类名
  if (item.isConsumable === 1 || item.isConsumable === true) {
    classes.push('consumable');
  }
  
  return classes.join(' ');
}

// 检查物品是否收藏
const isItemFavorite = (item) => {
  return item.isFavorite
}

// 添加/编辑物品表单
const itemForm = reactive({
  name: '',
  categoryId: null,
  brand: '',
  specification: '',
  price: 0,
  quantity: 1,
  locationId: null,
  purchaseDate: '',
  warranty: 12,
  status: 'active',
  notes: '',
  iconId: null,
  isFavorite: false
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入物品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  locationId: [{ required: true, message: '请选择位置', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 打开添加对话框
const openAddDialog = () => {
  Object.keys(itemForm).forEach(key => {
    if (key === 'price') {
      itemForm[key] = 0
    } else if (key === 'warranty') {
      itemForm[key] = 12
    } else if (key === 'purchaseDate') {
      itemForm[key] = new Date().toISOString().split('T')[0]
    } else if (key === 'status') {
      itemForm[key] = 'active'
    } else if (key === 'quantity') {
      itemForm[key] = 1
    } else if (key === 'isFavorite') {
      itemForm[key] = false
    } else if (key === 'locationId') {
      // 设置位置ID：优先使用界面选择的位置ID
      if (selectedLocationId.value) {
        itemForm[key] = selectedLocationId.value;
    } else {
        // 从localStorage获取当前位置ID
        const currentLocationId = localStorage.getItem('currentLocationId');
        if (currentLocationId) {
          itemForm[key] = currentLocationId;
        } else if (locations.value && locations.value.length > 0) {
          // 如果没有选择位置和localStorage中的位置，使用第一个可用位置
          itemForm[key] = locations.value[0].id;
        } else {
          itemForm[key] = null;
        }
      }
    } else {
      itemForm[key] = key === 'categoryId' ? null : ''
    }
  })
  // 使用新的物品详情模态框来添加物品
  itemToEdit.value = { ...itemForm }
  addDialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (item) => {
  console.log('Attempting to open detail modal for item:', JSON.stringify(item));
  itemToEdit.value = item
  detailModalVisible.value = true
  console.log('detailModalVisible set to:', detailModalVisible.value);
}

// 提交表单
const submitAddForm = async (newItem) => {
  try {
    console.log('接收到从ItemDetailModal传递的物品数据:', JSON.stringify(newItem));
    
    const itemToSubmit = {...newItem};
    if ('category' in itemToSubmit) {
      delete itemToSubmit.category;
    }
    
    // 重要：对于新添加的物品，强制使用当前选中的位置ID
    if (selectedLocationId.value) {
      itemToSubmit.locationId = selectedLocationId.value;
      console.log('[ItemList] 新增物品，强制使用当前选中的位置ID:', selectedLocationId.value);
    } else {
      // 如果没有选中的位置ID (例如在"全部位置"视图下添加)
      // 尝试从localStorage获取
      const currentLocationIdFromStorage = localStorage.getItem('currentLocationId');
      if (currentLocationIdFromStorage) {
        itemToSubmit.locationId = parseInt(currentLocationIdFromStorage) || currentLocationIdFromStorage;
        console.log('[ItemList] 新增物品，selectedLocationId未设置，使用localStorage中的位置ID:', itemToSubmit.locationId);
      } else if (locations.value && locations.value.length > 0) {
        // 使用第一个可用的位置作为后备
        itemToSubmit.locationId = locations.value[0].id;
        console.log('[ItemList] 新增物品，selectedLocationId和localStorage均未设置，使用第一个可用位置ID:', itemToSubmit.locationId);
      } else {
        console.error('[ItemList] 无法为新增物品确定位置ID。');
        ElMessage.error('请先选择一个位置，或确保系统中已配置位置信息。');
        return; // 阻止提交
      }
    }
    
    console.log('准备提交到store的数据:', JSON.stringify(itemToSubmit));
    console.log('itemsStore.addItem类型:', typeof itemsStore.addItem);
    
    // 确保调用添加方法并等待结果
    const result = await itemsStore.addItem(itemToSubmit);
    console.log('itemsStore.addItem调用完成，结果:', result);
    
    if (result && result.success) {

      // 刷新数据列表
      refreshItemData();
    } else {
  
    }
    
    // 关闭对话框
    addDialogVisible.value = false;
  } catch (error) {
    console.error('添加失败详细信息:', error);
    ElMessage.error(`添加操作失败: ${error.message || '未知错误'}`);
  }
}

// 新增：处理详情编辑模态框保存事件
const handleDetailSave = async (updatedItem) => {
  try {
    // 确保删除category字段，不传递给后端
    const itemToSubmit = {...updatedItem};
    if ('category' in itemToSubmit) {
      delete itemToSubmit.category;
    }
    
    await itemsStore.updateItem(updatedItem.id, itemToSubmit)
    
    // 更新成功后刷新数据
    await refreshItemData()
  
  } catch (error) {
    console.error('更新失败:', error)

  }
}

// 删除物品
const handleDelete = (item) => {
  ElMessageBox.confirm(`确定要删除 ${item.name} 吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await itemsStore.deleteItem(item.id)
      
      // 删除成功后刷新数据
      await refreshItemData()
      
     
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  return itemsStore.getCategoryName(categoryId)
}

// 获取位置名称
const getLocationName = (locationId) => {
  return itemsStore.getLocationName(locationId)
}

// 获取状态名称
const getStatusName = (status) => {
  return itemsStore.getStatusName(status)
}

// 分页处理
const handlePageChange = (page) => {
  itemsStore.setPage(page)
}

// 获取分类对应的CSS类名
const getCategoryClass = (item) => {
  if (!item.categoryId) return 'default'

  const category = categories.value.find(c => c.id === item.categoryId)
  if (!category) return 'default'

  switch (category.name) {
    case '电子设备': return 'electronics'
    case '家具': return 'furniture'
    case '厨房用品': return 'kitchen'
    case '卫浴用品': return 'bathroom'
    case '电器': return 'appliance'
    case '相机': return 'camera'
    default: return 'default'
  }
}

// 获取分类图标组件
const getCategoryIconComponent = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  if (!category) return More

  switch (category.name) {
    case '电子设备': return Cpu
    case '家具': return OfficeBuilding
    case '厨房用品': return Food
    case '卫浴用品': return ShoppingBag
    default: return More
  }
}

// 设置排序方式
const setSorting = (sortField) => {
  if (filters.sortBy === sortField) {
    // 如果已经按照这个字段排序，则切换排序顺序
    filters.sortOrder = filters.sortOrder === 'asc' ? 'desc' : 'asc'
  } else {
    // 否则设置新的排序字段，默认升序
    filters.sortBy = sortField
    filters.sortOrder = 'asc'
  }
}

// 修改itemIcons数组，使用名称作为标识符
const itemIcons = ref([
  // 基础图标
  { id: 1, name: 'box', category: '基础图标', label: '物品盒子' },
  { id: 2, name: 'tag', category: '基础图标', label: '标签' },
  { id: 3, name: 'calendar', category: '基础图标', label: '日历' },
  { id: 4, name: 'star', category: '基础图标', label: '收藏星星' },
  { id: 5, name: 'folder', category: '基础图标', label: '文件夹' },
  { id: 6, name: 'pin', category: '基础图标', label: '图钉' },
  { id: 7, name: 'key', category: '基础图标', label: '钥匙' },
  { id: 8, name: 'wallet', category: '基础图标', label: '钱包' },
  { id: 9, name: 'gift', category: '基础图标', label: '礼物' },
  { id: 10, name: 'heart', category: '基础图标', label: '爱心' },

  // 数码
  { id: 11, name: 'computer', category: '数码', label: '电脑' },
  { id: 12, name: 'laptop', category: '数码', label: '笔记本电脑' },
  { id: 13, name: 'tablet', category: '数码', label: '平板电脑' },
  { id: 14, name: 'phone', category: '数码', label: '手机' },
  { id: 15, name: 'watch', category: '数码', label: '手表' },
  { id: 16, name: 'headphone', category: '数码', label: '耳机' },
  { id: 17, name: 'camera', category: '数码', label: '相机' },
  { id: 18, name: 'gamepad', category: '数码', label: '游戏手柄' },
  { id: 19, name: 'mouse', category: '数码', label: '鼠标' },
  { id: 20, name: 'keyboard', category: '数码', label: '键盘' },

  // 首饰
  { id: 21, name: 'ring', category: '首饰', label: '戒指' },
  { id: 22, name: 'necklace', category: '首饰', label: '项链' },
  { id: 23, name: 'bracelet', category: '首饰', label: '手镯' },
  { id: 24, name: 'earrings', category: '首饰', label: '耳环' },
  { id: 25, name: 'diamond', category: '首饰', label: '钻石' },
  { id: 26, name: 'crown', category: '首饰', label: '皇冠' },

  // 美妆
  { id: 27, name: 'lipstick', category: '美妆', label: '口红' },
  { id: 28, name: 'perfume', category: '美妆', label: '香水' },
  { id: 29, name: 'makeup-brush', category: '美妆', label: '化妆刷' },
  { id: 30, name: 'mirror', category: '美妆', label: '镜子' },
  { id: 31, name: 'cream', category: '美妆', label: '面霜' },
  { id: 32, name: 'comb', category: '美妆', label: '梳子' },

  // 厨具
  { id: 33, name: 'bowl', category: '厨具', label: '碗' },
  { id: 34, name: 'chopsticks', category: '厨具', label: '筷子' },
  { id: 35, name: 'spoon', category: '厨具', label: '勺子' },
  { id: 36, name: 'fork', category: '厨具', label: '叉子' },
  { id: 37, name: 'knife', category: '厨具', label: '刀' },
  { id: 38, name: 'pot', category: '厨具', label: '锅' },
  { id: 39, name: 'pan', category: '厨具', label: '平底锅' },
  { id: 40, name: 'kettle', category: '厨具', label: '水壶' },
  { id: 41, name: 'cup', category: '厨具', label: '杯子' },
  { id: 42, name: 'oven', category: '厨具', label: '烤箱' },

  // 工具
  { id: 43, name: 'hammer', category: '工具', label: '锤子' },
  { id: 44, name: 'screwdriver', category: '工具', label: '螺丝刀' },
  { id: 45, name: 'pliers', category: '工具', label: '钳子' },
  { id: 46, name: 'wrench', category: '工具', label: '扳手' },
  { id: 47, name: 'saw', category: '工具', label: '锯子' },
  { id: 48, name: 'ruler', category: '工具', label: '尺子' },
  { id: 49, name: 'tape-measure', category: '工具', label: '卷尺' },
  { id: 50, name: 'scissors', category: '工具', label: '剪刀' },
  { id: 51, name: 'flashlight', category: '工具', label: '手电筒' },
  { id: 52, name: 'toolbox', category: '工具', label: '工具箱' },

  // 玩具
  { id: 53, name: 'blocks', category: '玩具', label: '积木' },
  { id: 54, name: 'puzzle', category: '玩具', label: '拼图' },
  { id: 55, name: 'rocket', category: '玩具', label: '火箭' },
  { id: 56, name: 'robot', category: '玩具', label: '机器人' },
  { id: 57, name: 'teddy-bear', category: '玩具', label: '泰迪熊' },
  { id: 58, name: 'doll', category: '玩具', label: '娃娃' },
  { id: 59, name: 'drum', category: '玩具', label: '鼓' },
  { id: 60, name: 'kite', category: '玩具', label: '风筝' },
  { id: 61, name: 'ball', category: '玩具', label: '球' },
  { id: 62, name: 'yo-yo', category: '玩具', label: '悠悠球' },

  // 运动
  { id: 63, name: 'basketball', category: '运动', label: '篮球' },
  { id: 64, name: 'football', category: '运动', label: '足球' },
  { id: 65, name: 'baseball', category: '运动', label: '棒球' },
  { id: 66, name: 'tennis', category: '运动', label: '网球' },
  { id: 67, name: 'pingpong', category: '运动', label: '乒乓球' },
  { id: 68, name: 'badminton', category: '运动', label: '羽毛球' },
  { id: 69, name: 'dumbbell', category: '运动', label: '哑铃' },
  { id: 70, name: 'swim-ring', category: '运动', label: '游泳圈' },
  { id: 71, name: 'skateboard', category: '运动', label: '滑板' },
  { id: 72, name: 'trophy', category: '运动', label: '奖杯' },

  // 家电
  { id: 73, name: 'refrigerator', category: '家电', label: '冰箱' },
  { id: 74, name: 'washing-machine', category: '家电', label: '洗衣机' },
  { id: 75, name: 'microwave', category: '家电', label: '微波炉' },
  { id: 76, name: 'tv', category: '家电', label: '电视' },
  { id: 77, name: 'air-conditioner', category: '家电', label: '空调' },
  { id: 78, name: 'desk-lamp', category: '家电', label: '台灯' },
  { id: 79, name: 'electric-fan', category: '家电', label: '电风扇' },
  { id: 80, name: 'power-socket', category: '家电', label: '电源插座' },
  { id: 81, name: 'refrigerator-vertical', category: '家电', label: '立式冰箱' },
  { id: 82, name: 'monitor', category: '家电', label: '显示器' },
  { id: 83, name: 'vacuum-cleaner', category: '家电', label: '吸尘器' },
  { id: 84, name: 'hair-dryer', category: '家电', label: '电吹风' },

  // 交通
  { id: 85, name: 'car', category: '交通', label: '汽车' },
  { id: 86, name: 'bus', category: '交通', label: '公交车' },
  { id: 87, name: 'truck', category: '交通', label: '卡车' },
  { id: 88, name: 'taxi', category: '交通', label: '出租车' },
  { id: 89, name: 'bike', category: '交通', label: '自行车' },
  { id: 90, name: 'motorcycle', category: '交通', label: '摩托车' },
  { id: 91, name: 'train', category: '交通', label: '火车' },
  { id: 92, name: 'airplane', category: '交通', label: '飞机' },
  { id: 93, name: 'ship', category: '交通', label: '轮船' },
  { id: 94, name: 'subway', category: '交通', label: '地铁' },

  // 服饰
  { id: 95, name: 'clothes', category: '服饰', label: '衣服' },
  { id: 96, name: 'tshirt', category: '服饰', label: 'T恤' },
  { id: 97, name: 'pants', category: '服饰', label: '裤子' },
  { id: 98, name: 'dress', category: '服饰', label: '连衣裙' },
  { id: 99, name: 'skirt', category: '服饰', label: '裙子' },
  { id: 100, name: 'coat', category: '服饰', label: '外套' },
  { id: 101, name: 'shoes', category: '服饰', label: '鞋子' },
  { id: 102, name: 'socks', category: '服饰', label: '袜子' },
  { id: 103, name: 'hat', category: '服饰', label: '帽子' },
  { id: 104, name: 'gloves', category: '服饰', label: '手套' },
  { id: 105, name: 'scarf', category: '服饰', label: '围巾' },
  { id: 106, name: 'shorts', category: '服饰', label: '短裤' },
])

// 修改图标分类列表，添加更多分类
const iconCategories = ['基础图标', '数码', '首饰', '美妆', '厨具', '工具', '玩具', '运动', '家电', '交通', '服饰']

// 添加图标选择器状态
const iconSelectorVisible = ref(false)
const iconFilter = ref('')
const selectedIconId = ref(null)
const activeIconTab = ref('基础图标')

// 图标选择器过滤方法
const filteredIcons = computed(() => {
  if (!iconFilter.value) {
    return itemIcons.value.filter(icon => {
      if (activeIconTab.value === '基础图标') return true
      return icon.category === activeIconTab.value
    })
  }
  return itemIcons.value.filter(icon =>
    (icon.name.toLowerCase().includes(iconFilter.value.toLowerCase()) ||
      icon.label.toLowerCase().includes(iconFilter.value.toLowerCase())) &&
    (activeIconTab.value === '基础图标' || icon.category === activeIconTab.value)
  )
})

// 打开图标选择器
const openIconSelector = () => {
  // 使用itemToEdit而不是itemForm
  selectedIconId.value = itemToEdit.value.iconId || null
  iconSelectorVisible.value = true
}

// 选择图标方法
const selectIcon = (iconId) => {
  selectedIconId.value = iconId
  console.log('选择的图标ID:', iconId);
  
  // 如果正在编辑物品，则更新itemToEdit
  if (itemToEdit.value) {
    // 先设置图标ID
    itemToEdit.value.iconId = iconId
    
    // 获取选中图标的分类
    const selectedIcon = itemIcons.value.find(icon => icon.id === iconId)
    console.log('选中的图标对象:', selectedIcon);
    
    if (selectedIcon) {
      // 根据图标分类设置物品分类
      const iconCategory = selectedIcon.category
      console.log('图标分类:', iconCategory);
      
      // 由于物品分类名称已与图标分类名称一致，直接按名称查找 ID
      const category = categories.value.find(c => c.name === iconCategory);
      const categoryId = category ? category.id : null; // 如果找不到则为 null

      console.log('可用的物品分类:', categories.value);
      console.log('映射后的分类ID:', categoryId);
      
      if (categoryId) {
        // 设置物品分类ID
        itemToEdit.value.categoryId = categoryId
        console.log('设置物品分类ID:', categoryId);
        
        // 删除category属性（如果存在）
        if ('category' in itemToEdit.value) {
          delete itemToEdit.value.category
        }
        
        移除图标分类提示
        ElMessage.success(`已根据选择的${iconCategory}图标自动将物品分类设置为${
          categories.value.find(c => c.id === categoryId)?.name || "对应分类"
        }`);
      }
    }
  }
  iconSelectorVisible.value = false
}

// 根据图标ID获取图标名称
const getIconNameById = (iconId) => {
  if (!iconId) return null
  const icon = itemIcons.value.find(icon => icon.id === iconId)
  return icon ? icon.name : null
}

// 根据物品获取合适的图标名称
const getItemIcon = (item) => {
  // 优先使用物品自己的iconId
  if (item.iconId) {
    const iconName = getIconNameById(item.iconId)
    if (iconName) return iconName
  }

  // 没有iconId时，根据分类返回默认图标
  const category = categories.value.find(c => c.id === item.categoryId)
  if (!category) return 'box'

  switch (category.name) {
    case '电子设备': return 'computer'
    case '家具': return 'folder'
    case '厨房用品': return 'knife'
    case '卫浴用品': return 'cup'
    case '电器': return 'refrigerator'
    case '相机': return 'camera'
    case '首饰': return 'ring'
    case '书籍': return 'folder'
    case '服装': return 'clothes'
    case '运动用品': return 'basketball'
    case '玩具': return 'blocks'
    case '工具': return 'hammer'
    case '美妆': return 'lipstick'
    case '车辆': return 'car'
    case '被子': case '被套': return 'box'
    case '枕头': case '枕套': return 'box'
    case '床单': return 'box'
    default: return 'box'
  }
}

// 引入useRoute以获取路由参数
const route = useRoute()

onMounted(async () => {
  // 从localStorage获取保存的位置ID
  const savedLocationId = localStorage.getItem('currentLocationId');
  if (savedLocationId) {
    selectedLocationId.value = savedLocationId;
    filters.locationId = savedLocationId;
    console.log('从localStorage初始化位置ID:', savedLocationId);
  }
  
    // 设置每页大小为12（确保先设置pageSize再获取数据）
    await itemsStore.setPageSize(12)
  
  let fetchItemsSuccess = true;
  let needMockData = false;
  
  // 分别处理每个API调用，独立捕获错误
  try {
    // 尝试从API加载物品数据
    await itemsStore.fetchItems()
  } catch (error) {
    console.error('加载物品数据失败:', error)
    fetchItemsSuccess = false;
    needMockData = true;
  }
  
  try {
    // 获取分类数据
    await itemsStore.fetchCategories()
  } catch (error) {
    console.error('加载分类数据失败:', error)
    // 分类加载失败不显示错误提示
  }
  
  
  try {
    // 获取状态数据
    await itemsStore.fetchStatuses()
  } catch (error) {
    console.error('加载状态数据失败:', error)
    // 状态加载失败不显示错误提示
  }
    
    // 添加滚动监听
    window.addEventListener('scroll', handleScroll)
  console.log('已添加滚动事件监听器，监听函数为handleScroll')
    
  // 只有在物品数据加载失败且需要使用模拟数据时才显示警告
  if (needMockData) {
    // 确保使用模拟数据作为后备
    if (itemsStore.items.length === 0 && typeof itemsStore.initMockData === 'function') {
      itemsStore.initMockData()
    ElMessage.warning('无法连接到后端服务，当前使用本地模拟数据')
    }
  }

  // 监听系统颜色模式变化以保持一致的UI风格
  if (window.matchMedia) {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
      // 更新暗黑模式状态（如果组件中有这个状态的话）
    })
  }

  // 移除对 initData 的调用，因为该函数未定义
  // await initData();
  
  // 测试添加物品方法
  window.testAddItem = () => {
    console.log('=== 测试添加物品功能 ===');
    const testItem = {
      name: '测试物品',
      categoryId: 1,
      locationId: 1,
      price: 100,
      quantity: 1,
      status: 'active',
      purchaseDate: new Date().toISOString().split('T')[0]
    };
    
    console.log('测试数据:', testItem);
    itemsStore.addItem(testItem)
      .then(result => {
        console.log('测试添加成功:', result);
      })
      .catch(error => {
        console.error('测试添加失败:', error);
      });
      
    // 直接使用axios测试
    window.testAxiosDirectly = () => {
      console.log('=== 直接使用Axios测试 ===');
      const axios = require('axios');
      const API_BASE_URL = 'http://localhost:8080/api';
      
      const testItem2 = {
        name: 'Axios直接测试物品',
        categoryId: 1,
        locationId: 1,
        price: 99.9,
        quantity: 1,
        status: 'active',
        purchaseDate: new Date().toISOString().split('T')[0]
      };
      
      // 获取token
      const token = localStorage.getItem('token');
      const headers = token ? { 
        'Authorization': `Bearer ${token}`, 
        'Content-Type': 'application/json' 
      } : { 
        'Content-Type': 'application/json' 
      };
      
      console.log('直接发送请求到:', `${API_BASE_URL}/items`);
      console.log('使用headers:', headers);
      console.log('发送数据:', testItem2);
      
      axios.post(`${API_BASE_URL}/items`, testItem2, { headers })
        .then(response => {
          console.log('Axios直接请求成功:', response.data);
        })
        .catch(error => {
          console.error('Axios直接请求失败:', error);
          if (error.response) {
            console.error('错误状态码:', error.response.status);
            console.error('错误数据:', error.response.data);
          }
        });
    };
  };

  // 初始化IntersectionObserver
  initObserver()
  nextTick(() => {
    observeLoadingTrigger()
    console.log('已在nextTick中注册观察器')
  })
  
  // 检查URL参数，如果有openAddDialog=true，则自动打开添加物品窗口
  if (route.query.openAddDialog === 'true') {
    console.log('检测到openAddDialog参数，自动打开添加物品窗口');
    nextTick(() => {
      openAddDialog();
    });
  }
})

// 刷新物品数据
const refreshItemData = async () => {
  loading.value = true
  try {
    // 重新获取物品数据
    await itemsStore.fetchItems()

    // 更新当前正在编辑的物品数据（如果有）
    if (itemToEdit.value && itemToEdit.value.id) {
      const updatedItem = await itemsStore.getItemById(itemToEdit.value.id)
      if (updatedItem) {
        itemToEdit.value = { ...updatedItem }
      }
    }

    // 移除刷新成功的消息提示
    // ElMessage.success('数据已刷新')
  } catch (error) {
    console.error('刷新数据失败:', error)
    // 即使失败也确保可以回退到模拟数据
    if (typeof itemsStore.initMockData === 'function' &&
      (!Array.isArray(itemsStore.items) || itemsStore.items.length === 0)) {
      itemsStore.initMockData()
    }
  } finally {
    loading.value = false
  }
}

// 新增：加载更多物品数据
const loadMoreItems = async () => {
  if (loadingMore.value || loading.value || allItemsLoaded.value) {
    console.log('跳过加载更多：loadingMore=', loadingMore.value, 'loading=', loading.value, 'allItemsLoaded=', allItemsLoaded.value)
    return
  }

  loadingMore.value = true
  console.log('开始加载更多物品')
  try {
    // 检查是否有分页信息
    if (!itemsStore.pagination) {
      console.error('分页信息不存在，无法加载更多物品')
      throw new Error('分页信息不存在')
    }
    
    // 计算下一页页码
    const nextPage = (itemsStore.pagination.currentPage || 1) + 1
    const totalPages = itemsStore.pagination.totalPages || 1
    console.log('当前页码:', itemsStore.pagination.currentPage, '总页数:', totalPages, '下一页:', nextPage)

    // 如果已经是最后一页，标记所有物品已加载完毕
    if (nextPage > totalPages) {
      console.log('已到达最后一页，无需再加载')
      allItemsLoaded.value = true
      return
    }

    // 记录加载前的物品数量
    const beforeCount = items.value.length
    console.log('加载前物品数量:', beforeCount)

    // 请求下一页数据
    console.log('调用store.loadMoreItems请求页码:', nextPage, '当前物品数量:', items.value.length)
    const result = await itemsStore.loadMoreItems(nextPage)
    console.log('加载更多物品结果:', result ? '成功' : '失败')
    
    // 强制更新视图数据（通过重新获取计算属性）
    nextTick(() => {
      const afterCount = items.value.length
      console.log('加载后物品数量:', afterCount, '新增物品:', afterCount - beforeCount)
      
      // 移除加载成功提示
      // if (afterCount > beforeCount) {
      //   ElMessage.success(`成功加载了${afterCount - beforeCount}个新物品`)
      // } else if (result) {
      //   ElMessage.warning('未加载到新物品')
      // }
      
      // 成功加载后再次检查观察器
      checkAndObserve()
    })
  } catch (error) {
    console.error('加载更多物品失败:', error)
    ElMessage.error(`加载物品失败: ${error.message}`)
  } finally {
    loadingMore.value = false
  }
}

// 新增：滚动监听函数
const handleScroll = () => {
  // 如果正在加载或已加载所有物品，则不处理
  if (loadingMore.value || allItemsLoaded.value) {
    console.log('滚动被忽略：loadingMore=', loadingMore.value, 'allItemsLoaded=', allItemsLoaded.value)
    return
  }

  // 获取视口底部位置和文档高度
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
  const clientHeight = document.documentElement.clientHeight || window.innerHeight
  
  // 计算距离底部的距离
  const distanceToBottom = scrollHeight - scrollTop - clientHeight
  console.log('滚动检测：距离底部', distanceToBottom, 'px')
  
  // 当滚动到距离底部300px时，触发加载更多（增加触发阈值）
  if (distanceToBottom < 300) {
    console.log('触发加载更多物品')
    loadMoreItems()
  }
}

// 添加IntersectionObserver实现
const loadingObserver = ref(null)
const loadingTriggerRef = ref(null)

// 初始化观察器
const initObserver = () => {
  if ('IntersectionObserver' in window) {
    console.log('初始化IntersectionObserver')
    loadingObserver.value = new IntersectionObserver((entries) => {
      const target = entries[0]
      if (target.isIntersecting && !loadingMore.value && !allItemsLoaded.value) {
        console.log('IntersectionObserver触发加载更多')
        loadMoreItems()
      }
    }, {
      root: null, // 使用视口作为根
      rootMargin: '100px', // 提前100px触发
      threshold: 0.1 // 只需要10%可见即触发
    })
  } else {
    console.log('浏览器不支持IntersectionObserver，将使用滚动监听')
  }
}

// 添加观察底部元素的方法
const observeLoadingTrigger = () => {
  if (loadingObserver.value && loadingTriggerRef.value) {
    console.log('开始观察底部加载触发元素')
    loadingObserver.value.observe(loadingTriggerRef.value)
  }
}

// 在DOM更新后观察底部元素
const checkAndObserve = () => {
  nextTick(() => {
    observeLoadingTrigger()
  })
}

// 在script部分添加过滤变量和计算属性
const consumableFilter = ref('all'); // 'all', 'consumable', 'non-consumable'

// 消耗品数量
const consumableItemsCount = computed(() => {
  return items.value.filter(item => item.isConsumable === 1 || item.isConsumable === true).length
})

// 非消耗品数量
const nonConsumableItemsCount = computed(() => {
  return items.value.filter(item => item.isConsumable !== 1 && item.isConsumable !== true).length
})

// 根据消耗品过滤器过滤项目
const filteredItemsByConsumable = computed(() => {
  if (consumableFilter.value === 'all') {
    return items.value;
  } else if (consumableFilter.value === 'consumable') {
    return items.value.filter(item => item.isConsumable === 1 || item.isConsumable === true);
  } else {
    return items.value.filter(item => item.isConsumable !== 1 && item.isConsumable !== true);
  }
});

// 切换消耗品过滤器
const toggleConsumableFilter = () => {
  if (consumableFilter.value === 'all') {
    consumableFilter.value = 'consumable';
  } else if (consumableFilter.value === 'consumable') {
    consumableFilter.value = 'non-consumable';
  } else {
    consumableFilter.value = 'all';
  }
}
</script>

<template>
  <div class="item-manager">
    <!-- 顶部区域 -->
    <div class="top-section">
      <!-- 资产统计卡片 - 左侧 -->
      <div class="asset-overview-wrapper">
        <div class="asset-overview-card">
          <div class="asset-header">
            <div class="asset-title">我的资产 {{ pagination.total ? `${pagination.total}/1` : '0/1' }}</div>
            <div class="asset-filter">全部 <i class="el-icon-arrow-down"></i></div>
          </div>

          <div class="asset-stats">
            <div class="asset-stat-item">
              <div class="stat-label">总资产</div>
              <div class="stat-value">¥{{ totalAssetValue }}</div>
            </div>
            <div class="asset-stat-divider"></div>
            <div class="asset-stat-item">
              <div class="stat-label">总日均</div>
              <div class="stat-value">¥{{ averageDailyCost }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 快速操作卡片 - 右侧 -->
      <div class="quick-actions-wrapper">
        <div class="quick-actions-card">
          <div class="quick-actions-title">快速操作</div>
          <div class="quick-actions-grid">
            <!-- 位置选择按钮 -->
            <div class="quick-action-item" @click="toggleLocationSelector">
              <div class="quick-action-icon location-icon">
                <el-icon>
                  <Location />
                </el-icon>
              </div>
              <div class="quick-action-text">
                {{ currentLocation || '全部位置' }}
              </div>
              <!-- 位置下拉菜单 -->
              <transition name="dropdown">
                <div v-if="showLocationSelector" class="location-dropdown">
                  <div class="location-item" :class="{ active: !selectedLocationId }"
                    @click.stop="selectLocation(null)">
                    全部位置
                  </div>
                  <div v-for="location in locations" :key="location.id" class="location-item"
                    :class="{ active: selectedLocationId === location.id }" @click.stop="selectLocation(location.id)">
                    {{ location.name }}
                  </div>
                </div>
              </transition>
            </div>

            <!-- 添加物品按钮 -->
            <div class="quick-action-item" @click="openAddDialog">
              <div class="quick-action-icon add-icon">
                <el-icon>
                  <Plus />
                </el-icon>
              </div>
              <div class="quick-action-text">添加物品</div>
            </div>

            <!-- 状态计数按钮 -->
            <div class="quick-action-item" @click="toggleConsumableFilter">
              <div class="quick-action-icon status-icon">
                <el-icon>
                  <HomeFilled />
                </el-icon>
              </div>
              <div class="quick-action-text">
                <template v-if="consumableFilter === 'all'">
                  {{ consumableItemsCount }}个消耗品 / {{ nonConsumableItemsCount }}个非消耗品
                </template>
                <template v-else-if="consumableFilter === 'consumable'">
                  仅显示消耗品 ({{ consumableItemsCount }})
                </template>
                <template v-else>
                  仅显示非消耗品 ({{ nonConsumableItemsCount }})
                </template>
              </div>
            </div>

            <!-- 视图切换按钮 -->
            <div class="quick-action-item" @click="viewMode = viewMode === 'list' ? 'grid' : 'list'">
              <div class="quick-action-icon view-icon">
                <el-icon v-if="viewMode === 'grid'">
                  <Menu />
                </el-icon>
                <el-icon v-else>
                  <Grid />
                </el-icon>
              </div>
              <div class="quick-action-text">
                {{ viewMode === 'grid' ? '列表视图' : '网格视图' }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 两栏布局：物品列表和筛选器侧边栏 -->
    <div class="main-content">
      <!-- 物品列表 - 主内容区 -->
      <div class="content-main">
        <!-- 过滤控制面板 -->
        <div class="filter-control-panel">
          <!-- 分类过滤按钮 -->
          <div class="filter-dropdown">
            <el-dropdown @command="(val) => filters.categoryId = val" trigger="click">
              <div class="filter-button">
                <span>分类</span>
                <el-icon>
                  <ArrowDown />
                </el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="null">全部分类</el-dropdown-item>
                  <el-dropdown-item v-for="category in categories" :key="category.id" :command="category.id">
                    {{ category.name }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 排序按钮 -->
          <div class="filter-dropdown">
            <el-dropdown @command="setSorting" trigger="click">
              <div class="filter-button">
                <span>排序</span>
                <el-icon>
                  <ArrowDown />
                </el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="name">
                    名称
                    <el-icon v-if="filters.sortBy === 'name' && filters.sortOrder === 'asc'">
                      <ArrowDown />
                    </el-icon>
                    <el-icon v-if="filters.sortBy === 'name' && filters.sortOrder === 'desc'">
                      <ArrowDown style="transform: rotate(180deg)" />
                    </el-icon>
                  </el-dropdown-item>
                  <el-dropdown-item command="price">
                    价格
                    <el-icon v-if="filters.sortBy === 'price' && filters.sortOrder === 'asc'">
                      <ArrowDown />
                    </el-icon>
                    <el-icon v-if="filters.sortBy === 'price' && filters.sortOrder === 'desc'">
                      <ArrowDown style="transform: rotate(180deg)" />
                    </el-icon>
                  </el-dropdown-item>
                  <el-dropdown-item command="purchaseDate">
                    购买日期
                    <el-icon v-if="filters.sortBy === 'purchaseDate' && filters.sortOrder === 'asc'">
                      <ArrowDown />
                    </el-icon>
                    <el-icon v-if="filters.sortBy === 'purchaseDate' && filters.sortOrder === 'desc'">
                      <ArrowDown style="transform: rotate(180deg)" />
                    </el-icon>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 状态过滤按钮 -->
          <div class="filter-dropdown">
            <el-dropdown @command="(val) => filters.status = val" trigger="click">
              <div class="filter-button">
                <span>状态</span>
                <el-icon>
                  <ArrowDown />
                </el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="null">全部状态</el-dropdown-item>
                  <el-dropdown-item v-for="status in statuses" :key="status.value" :command="status.value">
                    {{ status.label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 当前筛选条件展示 -->
          <div class="current-filters" v-if="filters.categoryId || filters.status || filters.sortBy !== 'name'">
            <span v-if="filters.categoryId">分类: {{ getCategoryName(filters.categoryId) }}</span>
            <span v-if="filters.status">状态: {{ getStatusName(filters.status) }}</span>
            <span v-if="filters.sortBy !== 'name'">排序: {{ filters.sortBy === 'price' ? '价格' : '日期' }} ({{
              filters.sortOrder ===
              'asc' ? '升序' : '降序' }})</span>
            <el-button type="text" size="small"
              @click="() => { filters.categoryId = null; filters.status = null; filters.sortBy = 'name'; filters.sortOrder = 'asc'; }">
              清除筛选
            </el-button>
          </div>
        </div>

        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" class="items-grid">
          <!-- 加载状态 -->
          <div v-if="loading && !items.length" class="loading-container">
            <div class="loading-spinner"></div>
            <p>加载物品数据中...</p>
          </div>
          <!-- 空数据状态 -->
          <div v-else-if="!items || items.length === 0" class="empty-state">
            <div class="empty-icon">📦</div>
            <h3>暂无物品</h3>
            <p>您还没有添加任何物品，或者没有符合筛选条件的物品</p>
            <el-button type="primary" @click="openAddDialog">添加物品</el-button>
          </div>
          <!-- 物品列表 -->
          <template v-else>
            <div v-for="item in filteredItemsByConsumable" :key="item.id" class="item-card" :class="getItemCardClass(item)"
              @click="openEditDialog(item)">
              <div class="item-card-content">
                <div class="item-icon">
                  <IconSvg :name="getItemIcon(item)" :size="50" color="#666" />
                </div>

                <div class="item-info">
                  <h3 class="item-name">{{ item.name }}</h3>
                  <div class="item-price">
                    <span class="item-original-price">¥{{ item.price }}</span>
                    <span class="item-dot">•</span>
                    <span class="item-daily-cost">¥{{ getDailyCost(item) }}/天</span>
                  </div>
                </div>

                <div class="item-days">{{ getOwnedDays(item) }}天</div>
              </div>
              
              <!-- 添加删除按钮 -->
              <button class="item-delete-btn" @click.stop="handleDelete(item)">
                <el-icon><Delete /></el-icon>
              </button>

              <div v-if="item.status === 'disposed'" class="item-status-badge">
                已退役
              </div>
              <div v-if="isItemFavorite(item)" class="item-favorite-badge">
                <el-icon>
                  <Star />
                </el-icon>
              </div>
            </div>
          </template>
          
          <!-- 添加底部加载状态 -->
          <div v-if="loadingMore" class="loading-more">
            <div class="loading-spinner-small"></div>
            <span>加载更多物品...</span>
          </div>
          <div v-if="allItemsLoaded && items.length > 0" class="no-more-items">
            已加载全部物品
          </div>
          <!-- 添加观察触发元素 -->
          <div ref="loadingTriggerRef" class="loading-trigger"></div>
        </div>

        <!-- 列表视图 -->
        <div v-else class="items-list">
          <!-- 加载状态 -->
          <div v-if="loading && !items.length" class="loading-container">
            <div class="loading-spinner"></div>
            <p>加载物品数据中...</p>
          </div>
          <!-- 空数据状态 -->
          <div v-else-if="!items || items.length === 0" class="empty-state">
            <div class="empty-icon">📝</div>
            <h3>暂无物品</h3>
            <p>您还没有添加任何物品，或者没有符合筛选条件的物品</p>
            <el-button type="primary" @click="openAddDialog">添加物品</el-button>
          </div>
          <!-- 物品列表 -->
          <div v-else v-for="item in filteredItemsByConsumable" :key="item.id" class="item-row" :class="getItemCardClass(item)">
            <div class="item-main-info">
              <div class="item-icon">
                <IconSvg :name="getItemIcon(item)" :size="40" color="#666" />
              </div>
              <div class="item-details">
                <h3 class="item-name">{{ item.name }}</h3>
                <div v-if="item.brand" class="item-brand">{{ item.brand }}</div>
                <div class="item-location">{{ getLocationName(item.locationId) }}</div>
              </div>
            </div>
            <div class="item-price-info">
              <div class="item-original-price">¥{{ item.price }}</div>
              <div class="item-daily-cost">¥{{ getDailyCost(item) }}/天</div>
            </div>
            <div class="item-days">{{ getOwnedDays(item) }}天</div>
            <div class="item-actions">
              <button class="action-button edit" @click="openEditDialog(item)">
                <el-icon>
                  <Edit />
                </el-icon>
              </button>
              <button class="action-button delete" @click="handleDelete(item)">
                <el-icon>
                  <Delete />
                </el-icon>
              </button>
            </div>
          </div>
          
          <!-- 添加底部加载状态 -->
          <div v-if="loadingMore" class="loading-more">
            <div class="loading-spinner-small"></div>
            <span>加载更多物品...</span>
          </div>
          <div v-if="allItemsLoaded && items.length > 0" class="no-more-items">
            已加载全部物品
          </div>
          <!-- 添加观察触发元素 -->
          <div ref="loadingTriggerRef" class="loading-trigger"></div>
        </div>
      </div>
    </div>

    <!-- 添加物品对话框 (使用与详情编辑相同的模态框) -->
    <ItemDetailModal v-model:visible="addDialogVisible" :item="itemToEdit" :categories="categories"
      :locations="locations" :statuses="statuses" :icons="itemIcons" @save="submitAddForm"
      @open-icon-selector="openIconSelector" ref="addItemModal" class="add-modal-ref" />

    <!-- 图标选择器弹窗 -->
    <el-dialog v-model="iconSelectorVisible" title="图标选择" width="90%" class="icon-selector-dialog">
      <div class="icon-search">
        <el-input v-model="iconFilter" placeholder="搜索图标" clearable prefix-icon="Search" />
      </div>

      <div class="icon-categories">
        <div v-for="category in iconCategories" :key="category" class="icon-category-tab"
          :class="{ active: activeIconTab === category }" @click="activeIconTab = category">
          {{ category }}
        </div>
      </div>

      <div class="icons-container">
        <div v-for="icon in filteredIcons" :key="icon.id" class="icon-item"
          :class="{ selected: selectedIconId === icon.id }" @click="selectIcon(icon.id)">
          <IconSvg :name="icon.name" :size="40" :color="selectedIconId === icon.id ? '#007aff' : '#666'" />
          <div class="icon-label">{{ icon.label || icon.name }}</div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="iconSelectorVisible = false">取消</el-button>
          <el-button type="primary" @click="iconSelectorVisible = false">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增：物品详情编辑模态框 -->
    <ItemDetailModal v-model:visible="detailModalVisible" :item="itemToEdit" :categories="categories"
      :locations="locations" :statuses="statuses" :icons="itemIcons" @save="handleDetailSave" @refresh="refreshItemData"
      @open-icon-selector="openIconSelector" ref="detailModal" class="detail-modal-ref" />

  </div>
</template>

<style scoped>
.item-manager {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  max-width: 100%;
  margin: 0 auto;
  min-height: 100vh;
  position: relative;
}

/* 顶部区域样式 */
.top-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  gap: 20px;
}

/* 资产统计卡片样式 */
.asset-overview-wrapper {
  width: 50%;
  height: 300px;
  /* 保持与快速操作卡片一致 */
}

.asset-overview-card {
  background-color: #1a73e8;
  border-radius: 16px;
  padding: 30px; /* 减少内边距 */
  color: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 调整内容分布 */
}

.asset-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* margin-bottom: 15px; */ /* 移除固定底部边距，让flex布局自动分配 */
}

.asset-title {
  font-size: 30px; /* 加大标题字号 */
  font-weight: 500;
}

.asset-filter {
  font-size: 20px;
  display: flex;
  align-items: center;
}

.asset-stats {
  display: flex;
  align-items: center;
  /* margin-top: auto; */ /* 移除，让flex自动分配 */
}

.asset-stat-item {
  flex: 1;
}

.asset-stat-divider {
  width: 1px;
  height: 50px; /* 增加分割线高度 */
  background-color: rgba(255, 255, 255, 0.2);
  margin: 0 25px; /* 调整分割线边距 */
}

.stat-label {
  font-size: 25px; /* 加大标签字号 */
  color: rgba(255, 255, 255, 0.85); /* 稍微调亮 */
  margin-bottom: 8px; /* 增加与数值的间距 */
}

.stat-value {
  font-size: 40px; /* 显著加大数值字号 */
  font-weight: 600;
}

/* 快速操作卡片样式 */
.quick-actions-wrapper {
  width: 50%;
  height: 300px;
  /* 增加高度给底部按钮更多空间 */
}

.quick-actions-card {
  background-color: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.quick-actions-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 15px;
  /* 减少顶部标题的下边距 */
  color: #333;
}

.quick-actions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 15px;
  flex-grow: 1;
  height: calc(100% - 35px);
  /* 确保网格有固定高度 */
}

.quick-action-item {
  background-color: #f5f5f7;
  border-radius: 12px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
  height: 100%;
  /* 确保每个按钮占满网格单元 */
}

.quick-action-item:hover {
  background-color: #e9e9eb;
}

.quick-action-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
}

.location-icon {
  color: #1a73e8;
  background-color: rgba(26, 115, 232, 0.1);
}

.add-icon {
  color: #34a853;
  background-color: rgba(52, 168, 83, 0.1);
}

.status-icon {
  color: #fbbc05;
  background-color: rgba(251, 188, 5, 0.1);
}

.view-icon {
  color: #ea4335;
  background-color: rgba(234, 67, 53, 0.1);
}

.quick-action-text {
  font-size: 14px;
  color: #333;
  text-align: center;
}

/* 位置下拉菜单样式 */
.location-dropdown {
  position: absolute;
  top: calc(100% + 5px);
  left: 0;
  width: 200px;
  background-color: white;
  border-radius: 12px;
  padding: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  z-index: 100;
}

/* 修改视图控制容器样式，因为我们移除了其内容 */
.view-control-container {
  display: none;
  /* 隐藏原来的视图控制容器 */
}

/* 响应式调整 */
@media (max-width: 768px) {
  .top-section {
    flex-direction: column;
  }

  .asset-overview-wrapper,
  .quick-actions-wrapper {
    width: 100%;
    margin-bottom: 20px;
    /* 增加垂直间距 */
  }

  .quick-actions-wrapper {
    height: 240px;
    /* 确保在小屏幕上也有足够高度 */
  }
}

/* 筛选按钮苹果风格 */
.filter-dropdown {
  margin-right: 12px;
}

.filter-button {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #d8d8dd;
  border-radius: 18px;
  border: 1px solid rgba(0, 0, 0, 0.05);
  font-size: 16px;
  color: #282829;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-button:hover {
  background-color: #E5E5EA;
  transform: translateY(-1px);
}

.filter-button span {
  margin-right: 6px;
}

.filter-control-panel {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 20px;
}

.current-filters {
  margin-left: 12px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.current-filters span {
  background-color: #f0f0f3;
  padding: 5px 12px;
  border-radius: 14px;
  font-size: 15px;
  color: #2d2d2e;
}

/* 下拉菜单苹果风格 */
:deep(.el-dropdown-menu) {
  border-radius: 10px !important;
  padding: 6px !important;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15) !important;
  border: none !important;
  background-color: white !important;
}

:deep(.el-dropdown-menu__item) {
  font-size: 16px !important;
  color: #333 !important;
  border-radius: 6px !important;
  padding: 10px 16px !important;
  margin: 2px 0 !important;
  text-align: center !important;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: #f5f5f7 !important;
}

:deep(.el-dropdown-menu__item.is-active),
:deep(.el-dropdown-menu__item:focus) {
  background-color: #007aff !important;
  color: white !important;
  font-weight: normal !important;
}

/* 选中状态样式 */
:deep(.el-dropdown-menu__item.selected),
:deep(.el-dropdown-menu__item.el-dropdown-menu__item--divided) {
  background-color: #007aff !important;
  color: white !important;
}

/* 设置弹出层样式 */
:deep(.el-popper.is-light) {
  border: none !important;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1) !important;
}

/* 针对特定样式覆盖 */
.el-select-dropdown.is-multiple .el-select-dropdown__item.selected {
  background-color: #007aff !important;
  color: white !important;
}

/* 特殊处理全部状态选项 */
:deep(.el-select-dropdown__item:first-child),
:deep(.el-dropdown-menu__item:first-child) {
  margin-top: 0 !important;
}

/* 统一对话框和表单样式 */
:deep(.el-dialog) {
  border-radius: 16px !important;
  overflow: hidden !important;
}

:deep(.el-dialog__header) {
  margin: 0 !important;
  padding: 20px 20px 10px !important;
  text-align: center !important;
}

:deep(.el-dialog__title) {
  font-weight: 500 !important;
  font-size: 18px !important;
}

:deep(.el-dialog__body) {
  padding: 10px 24px 20px !important;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px !important;
  text-align: right !important;
}

:deep(.el-dialog .el-form-item__label) {
  font-weight: 500 !important;
}

/* 统一表单元素圆角 */
:deep(.el-input__wrapper),
:deep(.el-textarea__inner),
:deep(.el-select .el-input__wrapper),
:deep(.el-date-editor.el-input__wrapper),
:deep(.el-input-number .el-input__wrapper) {
  border-radius: 12px !important;
  padding: 0 15px !important;
}

:deep(.el-button) {
  border-radius: 12px !important;
}

:deep(.el-button--primary) {
  background-color: #007aff !important;
  border-color: transparent !important;
}

:deep(.el-button--primary:hover) {
  background-color: #0062cc !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 2px 6px rgba(0, 122, 255, 0.3) !important;
}

:deep(.el-input-number__increase),
:deep(.el-input-number__decrease) {
  border-radius: 50% !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

:deep(.el-date-editor .el-input__wrapper) {
  padding: 0 15px !important;
}

/* 网格视图样式 */
.items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.item-card {
  background-color: white;
  border-radius: 16px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border: 1px solid rgba(0, 0, 0, 0.05);
  height: 150px;
  /* 增加高度为原来的1.5倍 */
}

.item-card-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 100%;
}

.item-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

/* 移除边框标记样式 */
.card-electronics,
.card-furniture,
.card-kitchen,
.card-bathroom,
.card-appliance,
.card-camera,
.card-default {
  border-left: none;
}

/* 使用圆形色标来区分类别 */
.item-card::before {
  content: '';
  position: absolute;
  top: 15px;
  left: 15px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  z-index: 2;
}

.card-electronics::before {
  background-color: rgb(76, 217, 100);
  box-shadow: 0 0 6px rgba(76, 217, 100, 0.7);
}

.card-furniture::before {
  background-color: rgb(90, 200, 250);
  box-shadow: 0 0 6px rgba(90, 200, 250, 0.7);
}

.card-kitchen::before {
  background-color: rgb(255, 204, 0);
  box-shadow: 0 0 6px rgba(255, 204, 0, 0.7);
}

.card-bathroom::before {
  background-color: rgb(88, 86, 214);
  box-shadow: 0 0 6px rgba(88, 86, 214, 0.7);
}

.card-appliance::before {
  background-color: rgb(255, 149, 0);
  box-shadow: 0 0 6px rgba(255, 149, 0, 0.7);
}

.card-camera::before {
  background-color: rgb(162, 132, 94);
  box-shadow: 0 0 6px rgba(162, 132, 94, 0.7);
}

.card-default::before {
  background-color: rgb(0, 122, 255);
  box-shadow: 0 0 6px rgba(0, 122, 255, 0.7);
}

/* 列表视图中的圆形色标 */
.item-row::before {
  content: '';
  width: 10px;
  height: 10px;
  border-radius: 50%;
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
}

.item-row {
  padding-left: 35px;
  /* 给色标腾出空间 */
}

.item-status-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.1);
  color: #333;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  z-index: 1;
}

.item-favorite-badge {
  position: absolute;
  top: 10px;
  right: 50px; /* 向左移动，避免与删除按钮重叠 */
  color: #ff9500;
  z-index: 1;
}

.item-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-color: #f5f5f7;
}

.item-info {
  flex-grow: 1;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 8px 0;
}

.item-price {
  font-size: 14px;
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.item-original-price {
  font-weight: 500;
}

.item-dot {
  margin: 0 5px;
}

.item-daily-cost {
  opacity: 0.8;
}

.item-days {
  font-size: 14px;
  text-align: right;
}

/* 列表视图样式 */
.items-list {
  background-color: white;
  border-radius: 16px;
  overflow: hidden;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.item-row {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: white;
  position: relative;
}

/* 使用更微妙的列表视图样式 */
.item-row::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
}

.item-row.card-electronics::before {
  background-color: rgba(76, 217, 100, 0.7);
}

.item-row.card-furniture::before {
  background-color: rgba(90, 200, 250, 0.7);
}

.item-row.card-kitchen::before {
  background-color: rgba(255, 204, 0, 0.7);
}

.item-row.card-bathroom::before {
  background-color: rgba(88, 86, 214, 0.7);
}

.item-row.card-appliance::before {
  background-color: rgba(255, 149, 0, 0.7);
}

.item-row.card-camera::before {
  background-color: rgba(162, 132, 94, 0.7);
}

.item-row.card-default::before {
  background-color: rgba(0, 122, 255, 0.7);
}

.item-main-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.item-details {
  margin-left: 15px;
}

.item-brand,
.item-location {
  color: #86868b;
  font-size: 13px;
}

.item-price-info {
  margin-right: 20px;
  text-align: right;
}

.item-actions {
  display: flex;
  gap: 10px;
}

.action-button {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-button:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

/* 状态筛选卡片样式 */
.status-filters {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.status-item {
  padding: 10px 12px;
  background-color: #f5f5f7;
  border-radius: 6px;
  font-size: 13px;
  color: #1d1d1f;
  cursor: pointer;
  transition: all 0.2s;
}

.status-item:hover {
  background-color: #e6e6e6;
}

.status-item.active {
  background-color: #0071e3;
  color: white;
}

/* 排序选项样式 */
.sort-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.sort-item {
  padding: 10px 12px;
  background-color: #f5f5f7;
  border-radius: 6px;
  font-size: 13px;
  color: #1d1d1f;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
}

.sort-item:hover {
  background-color: #e6e6e6;
}

.sort-item.active {
  background-color: #0071e3;
  color: white;
}

/* 表单样式 */
.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 18px;
}

.form-col {
  flex: 1;
  margin-bottom: 0 !important;
}

.full-width {
  width: 100%;
}

.price-input {
  width: 100%;
}

:deep(.el-input-number.price-input .el-input__wrapper) {
  width: 100%;
}

/* 表单字段样式优化 */
:deep(.el-form-item__label) {
  padding-right: 12px;
  font-size: 14px;
  color: #606266;
}

/* 确保表单在移动设备上仍然可用 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 0;
  }

  .form-col {
    margin-bottom: 18px !important;
  }
}

/* 优化表单内部元素的间距 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.asset-dialog .el-dialog__body) {
  padding: 10px 24px 20px !important;
}

/* 增强表单文字和线条可见性 */
.enhanced-form :deep(.el-form-item__label) {
  font-weight: 500 !important;
  font-size: 15px !important;
  color: #333 !important;
}

.enhanced-form :deep(.el-form-item__label::before) {
  color: #ff4d4f !important;
  font-weight: bold !important;
  font-size: 16px !important;
}

.enhanced-form :deep(.el-input__wrapper),
.enhanced-form :deep(.el-textarea__inner),
.enhanced-form :deep(.el-select .el-input__wrapper),
.enhanced-form :deep(.el-date-editor.el-input__wrapper),
.enhanced-form :deep(.el-input-number .el-input__wrapper) {
  border: 1px solid #ccc !important;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) !important;
}

.enhanced-form :deep(.el-input__wrapper:hover),
.enhanced-form :deep(.el-textarea__inner:hover),
.enhanced-form :deep(.el-select .el-input__wrapper:hover),
.enhanced-form :deep(.el-date-editor.el-input__wrapper:hover),
.enhanced-form :deep(.el-input-number .el-input__wrapper:hover) {
  border-color: #062d57 !important;
  box-shadow: 0 0 0 1px rgba(0, 122, 255, 0.3) !important;
}

.enhanced-form :deep(.el-input__wrapper.is-focus),
.enhanced-form :deep(.el-textarea__inner:focus),
.enhanced-form :deep(.el-select .el-input__wrapper.is-focus),
.enhanced-form :deep(.el-date-editor.el-input__wrapper.is-focus),
.enhanced-form :deep(.el-input-number .el-input__wrapper.is-focus) {
  border-color: #03305f;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2) !important;
}

.enhanced-form :deep(.el-input__inner),
.enhanced-form :deep(.el-textarea__inner) {
  color: #333 !important;
  font-size: 14px !important;
}

/* 分割线样式增强 */
.enhanced-form .form-row {
  position: relative;
}

/* 选择器下拉箭头颜色加深 */
.enhanced-form :deep(.el-select__icon),
.enhanced-form :deep(.el-input__icon) {
  color: #555 !important;
}

/* 日期选择器图标颜色加深 */
.enhanced-form :deep(.el-range__icon),
.enhanced-form :deep(.el-input__prefix-icon) {
  color: #555 !important;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e8e8e8 !important;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #e8e8e8 !important;
}

/* 图标选择器样式 */
.icon-selector-trigger {
  width: 120px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
  transition: all 0.3s;
}

.icon-selector-trigger:hover {
  border-color: #007aff;
  background-color: #f0f7ff;
}

.icon-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8c8c8c;
}

.icon-placeholder .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.selected-icon {
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.selected-icon img {
  max-width: 100%;
  max-height: 100%;
}

.icon-selector-dialog {
  --el-dialog-padding-primary: 16px;
}

.icon-search {
  margin-bottom: 16px;
}

.icon-categories {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
  overflow-x: auto;
}

.icon-category-tab {
  padding: 8px 16px;
  cursor: pointer;
  position: relative;
  white-space: nowrap;
}

.icon-category-tab.active {
  color: #007aff;
  font-weight: 500;
}

.icon-category-tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #007aff;
}

.icons-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding: 4px;
}

.icon-item {
  width: 80px;
  height: 80px;
  border: 1px solid #eee;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  padding: 8px;
  transition: all 0.2s;
  background-color: #fff;
}

.icon-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-color: #007aff;
}

.icon-item.selected {
  border: 2px solid #007aff;
  background-color: #f0f7ff;
}

.icon-label {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

.icon-item.selected .icon-label {
  color: #007aff;
  font-weight: 500;
}

@media (max-width: 768px) {
  .icons-container {
    grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
  }

  .icon-item {
    width: 60px;
    height: 60px;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  width: 100%;
  padding: 2rem;
  text-align: center;
  color: #86868b;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 3px solid rgba(0, 113, 227, 0.1);
  border-top-color: #0071e3;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  width: 100%;
  padding: 2rem;
  text-align: center;
  color: #86868b;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.7;
}

.empty-state h3 {
  font-size: 1.2rem;
  font-weight: 500;
  margin: 0 0 0.5rem;
  color: #1d1d1f;
}

.empty-state p {
  margin-bottom: 1.5rem;
  max-width: 300px;
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 1rem;
  color: #86868b;
  font-size: 14px;
}

.loading-spinner-small {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid rgba(0, 113, 227, 0.2);
  border-top-color: #0071e3;
  animation: spin 0.8s linear infinite;
  margin-right: 0.5rem;
}

.no-more-items {
  margin-top: 0.5rem;
  color: #86868b;
  font-size: 14px;
}

/* 消耗品标识 - 左上角绿色圆点 */
.item-card.consumable::before {
  content: '';
  position: absolute;
  top: 10px;
  left: 10px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #34c759; /* 绿色 */
  z-index: 1;
}

.item-row.consumable::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 10px;
  transform: translateY(-50%);
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #34c759; /* 绿色 */
  z-index: 1;
}

.quick-action-item {
  cursor: pointer;
  transition: all 0.2s ease;
}

.quick-action-item:hover {
  transform: translateY(-2px);
}

/* 添加底部触发元素样式 */
.loading-trigger {
  height: 20px;
  margin-top: 10px;
  width: 100%;
}

/* 添加删除按钮样式 */
.item-delete-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.1);
  color: #ff3b30;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  opacity: 0;
  transition: all 0.2s ease;
  z-index: 3;
}

.item-card:hover .item-delete-btn {
  opacity: 1;
}

.item-delete-btn:hover {
  background-color: #ff3b30;
  color: white;
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(255, 59, 48, 0.4);
}

.dark-mode .item-delete-btn {
  background-color: rgba(44, 44, 46, 0.8);
  border-color: rgba(255, 255, 255, 0.1);
}

.item-icon {
  width: 64px;
  height: 64px;
}
</style>